package org.gl.training.planner.mdb;

import java.util.Properties;

import javax.ejb.MessageDriven;
import javax.jms.Message;
import javax.jms.MessageListener;
import javax.jms.ObjectMessage;
import javax.mail.PasswordAuthentication;
import javax.mail.Session;
import javax.mail.Transport;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeMessage;

import org.gl.training.planner.model.MailMessage;

@MessageDriven(mappedName = "jms/EmailQueue")
public class EmailMdb implements MessageListener {

//	@Resource(mappedName = "mail/EMailSession")
//	private Session session;

	@Override
	public void onMessage(Message msg) {
		ObjectMessage objMessage = (ObjectMessage) msg;
		try {
			MailMessage mailMessage = (MailMessage) objMessage.getObject();

			final String username = "plannerdaily@gmail.com";
			final String password = "Qwerty12345";

			Properties props = new Properties();
			props.put("mail.smtp.auth", "true");
			props.put("mail.smtp.starttls.enable", "true");
			props.put("mail.smtp.host", "smtp.gmail.com");
			props.put("mail.smtp.port", "587");

			Session session = Session.getInstance(props,
					new javax.mail.Authenticator() {
						protected PasswordAuthentication getPasswordAuthentication() {
							return new PasswordAuthentication(username,
									password);
						}
					});
			
			MimeMessage message = new MimeMessage(session);
			message.setFrom(new InternetAddress("plannerdaily@gmail.com"));
			message.setRecipients(javax.mail.Message.RecipientType.TO,
					InternetAddress.parse(mailMessage.getTo()));
			message.setSubject(mailMessage.getSubject());
			message.setText(mailMessage.getBody());
			Transport.send(message);
		} catch (Exception e) {
			e.printStackTrace();
		}
	}

}
